package com.papper.common.bean;

import com.alibaba.fastjson.JSON;

import javax.persistence.Id;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * @author 辣椒1228
 */
public abstract class BaseEntity {

    /**
     * 返回主键
     *
     * @return Serializable id
     */
    public Serializable id() {
        try {
            Class      cla = (Class) this.getClass();
            Field[]    fs  = cla.getDeclaredFields();
            Annotation annotation;
            for (int i = 0; i < fs.length; i++) {
                Field f = fs[i];
                f.setAccessible(true);
                annotation = f.getAnnotation(Id.class);
                if (annotation != null) {
                    return (Serializable) f.get(this);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
